import React, { memo } from "react";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { Form, Input, Button, message } from "antd";
const Login = memo(() => {
  let navigate = useNavigate();
  // 拿到from表单的实例
  let [from] = Form.useForm();
  // 实现校验
  const validateMessages = {
    required: "${label} 是必选字段",
    types: {
      email: "${label}不是合法的email地址!",
      number: "${label}不是合法的数字!",
    },
    string: {
      min: "${label}至少应该是${min}位长度的字符串",
    },
  };
  const submit = (values) => {
    from
      .validateFields()
      .then(async (values) => {
        const res = await axios.post("http://localhost:3000/login", values);
        if (!res.data.success) {
          return message.error("登录失败");
        }
        // 存一下服务端返回的token
        const token = res.data.data.token;
        localStorage.setItem("token", token);
        if (token) {
          navigate("/list");
        }
      })
      .catch((errorInfo) => {
        const str = errorInfo.errorFields[0].errors[0];
        message.error(str);
      });
  };
  return (
    <div>
      <Form
        validateMessages={validateMessages}
        form={from}
        onFinish={() => submit()}
      >
        <Form.Item
          label="用户名"
          name="username"
          rules={[
            {
              required: true, // 非空
            },

            {
              type: "string",
              min: 5,
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item
          label="密码"
          name="password"
          rules={[
            {
              required: true, // 非空
            },
            {
              type: "types",
            },
            {
              type: "string",
              min: 6,
            },
          ]}
        >
          <Input />
        </Form.Item>
        <Form.Item>
          <Button type="primary" htmlType="submit" onClick={() => submit()}>
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
});

export default Login;
